package com.lemon.core.utils;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 李猛
 * @datetime 2023/12/15 9:19
 * @description 类对象
 */
@Slf4j
public class ConverterUtil {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 数据转换-传唤成对象
     *
     * @param request 入参
     * @param target  返回值
     * @param <R>
     * @return
     */
    public static <R> R toBean(HttpServletRequest request, Class<R> target) {
        if (request == null) {
            return null;
        }
        try {
            return objectMapper.readValue(request.getInputStream(), target);
        } catch (IOException e) {
            log.error("ConverterUtil.toBean.error,message:{}", e.getMessage());
        }
        return null;
    }

    /**
     * 数据转换-传唤成对象
     *
     * @param source 入参
     * @param target 返回值
     * @param <R>
     * @return
     */
    public static <R> R toBean(Object source, Class<R> target) {
        if (source == null) {
            return null;
        }
        String jsonStr = JSONUtil.toJsonStr(source);
        return JSONUtil.toBean(jsonStr, target);
    }

    /**
     * 实体类对象转Map
     *
     * @param source
     * @param <T>
     * @return
     */
    public static <T> Map<String, Object> toMap(T source) {
        //1.获取实体类中的所有属性
        Field[] fields = source.getClass().getDeclaredFields();

        //2.初始化返回值
        Map<String, Object> result = new HashMap<>();

        //3.通过反射获取属性的值
        for (Field field : fields) {
            //3.1.设置字段是否可访问
            boolean accessible = field.isAccessible();
            if (!accessible) {
                field.setAccessible(true);
            }

            //3.2.获取字段名
            String name = field.getName();

            try {
                //3.3.获取字段的值
                Object object = field.get(source);
                result.put(name, object);
            } catch (IllegalAccessException e) {
                log.error("ConverterUtil.toMap.error,message:{}", e.getMessage());
            }

            if (!accessible) {
                field.setAccessible(false);
            }
        }

        return result;
    }

    /**
     * 数据转换-传唤成List
     *
     * @param source
     * @param target
     * @param <R>
     * @return
     */
    public static <R> List<R> toList(Object source, Class<R> target) {
        String jsonStr = JSONUtil.toJsonStr(source);
        return JSONUtil.toList(jsonStr, target);
    }
}
